<?php

namespace Yolo\Utils;

class Path
{
    /**
     * 格式化路径（前后加上/）
     * @param string $path 路径
     * @return string
     */
    public static function formatPath(string $path): string
    {
        return '/' . trim($path, '/') . '/';
    }

    /**
     * 解析restful的path
     * @param string $path
     * @return array
     */
    public static function parseUri(string $path): array
    {
        $pattern ='/\{([^}]+)}/';

        $path = trim($path, '/');

        $paths = explode('/', $path);

        $type = 'static';

        $variables = [];
        foreach ($paths as $item) {
            if ($item === '') {
                continue;
            }

            if (preg_match('/^\{([^}]+)}$/', $item, $matches)) {

                $variables[] = $matches[1];
                $type = 'pattern';
            }
        }

        if ($type === 'pattern') {
            $handled = preg_replace($pattern, '([^/]*)', $path);
            $pathPattern = '/^\/'.str_replace('/', '\/', $handled).'\/$/';
        }

        return [
            'type' => $type,
            'pattern' => $pathPattern ?? '',
            'variables' => $variables,
        ];
    }
}
